package com.atguigu.mvc.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import java.io.IOException;
import java.io.InputStream;

@Controller
public class DownloadHandler {

    @Autowired
    private ServletContext servletContext;

    @RequestMapping("/loaddown/for/picture")
    public ResponseEntity<byte[]> loadDownFile() throws IOException {

        // 通过 servletContext 对象将要下载的文件读取到内存中
        InputStream inputStream = servletContext.getResourceAsStream("/download/27A99F9A335C4106BD8B2E8B8C1EB288.jpg");

        // 通过输入流对象获取被下载的文件的长度
        int fileLength = inputStream.available();

        // 创建字节数组，保存要下载文件的二进制数据
        byte[] buffer = new byte[fileLength];

        // 将文件数据读取到字节数组中
        inputStream.read(buffer);

        // 创建 MultiValueMap 对象封装响应消息头数据
        MultiValueMap responseHeaders = new HttpHeaders();

        // 设置响应消息头
        // Content-Disposition: attachment;filename=xxx.jpg
        // 作用是告诉浏览器：当前这个响应数据作为附件处理，给用户显示下载文件下载界面；通过 filename 指定文件名
        responseHeaders.add("Content-Disposition", "attachment;filename=27A99F9A335C4106BD8B2E8B8C1EB288.jpg");

        // 创建 ResponseEntity 对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(buffer, responseHeaders, HttpStatus.OK);

        return responseEntity;
    }

}
